import { App } from 'vue'
import { RouteRecordRaw, createRouter, createWebHashHistory } from 'vue-router'

const homepageModules = import.meta.glob('../router/modules/homepage.ts', { eager: true })

const baseRoutes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/report/report-git'
  }
]

// 固定路由模块转换为路由
export function mapModuleRouterList(modules: Record<string, unknown>): Array<RouteRecordRaw> {
  const routerList: Array<RouteRecordRaw> = []
  Object.keys(modules).forEach((key) => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const mod = (modules[key] as any).default || {}
    const modList = Array.isArray(mod) ? [...mod] : [mod]
    routerList.push(...modList)
  })
  return routerList
}

export const homepageRouterList: Array<RouteRecordRaw> = mapModuleRouterList(homepageModules)

const routes = [...baseRoutes, ...homepageRouterList]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return {
      el: '#app',
      top: 0,
      behavior: 'smooth'
    }
  }
})

export function setupRouter(app: App) {
  app.use(router)
}
